<template>
  <div>
    <div style="width: 100%;" class="box">
      <img style="width: 100%;height:auto" :src="img" alt="" />
    </div>
    <view class="algorithmicList">
      <view
        class="algorithmicListCell"
        v-for="(model, index) in listDataSource"
        :key="index"
        @click="openAlgorithmicInfo(model)"
      >
        <view class="algorithmicListCellContainerView">
          <view class="cellLeftStack">
            <view class="cellTitleStack" style="height: 35rpx;">
              <text class="cellTitle">{{ model.cnName }}</text>
              <text class="cellContent1" style="margin-left: 10rpx;">{{
                model.endTime
              }}</text>
            </view>
            <view class="cellTitleStack" style="height: 30rpx;">
              <view
                class="cellDot"
                style="background-color: #53A6DB; margin-top: 5rpx;"
              ></view>
              <text class="cellContent1" style="margin-left: 10rpx;"
                >收益率曲线图</text
              >
              <view
                class="cellDot"
                style="background-color: #E67F4A; margin-top: 5rpx; margin-left: 10rpx;"
              ></view>
              <text class="cellContent1" style="margin-left: 10rpx;"
                >沪深300</text
              >
            </view>
            <view class="cellChartView">
              <canvas
                :canvas-id="model.cnName"
                :id="model.cnName"
                class="charts"
              ></canvas>
            </view>
          </view>
          <view class="cellRightStack">
            <view class="cellRightTop">
              <view class="cellAutherView" @click="subscribe">
                <text class="cellContent1">{{ subscribeText }}</text>
              </view>
              <image
                src="../../static/img/arrows_right_icon.png"
                mode="aspectFill"
                style="width: 20rpx; height: 20rpx; margin-left: auto;"
              ></image>
            </view>
            <text
              class="cellTitle"
              style="margin-top: 20rpx; text-align: center;"
              >累计收益</text
            >
            <view class="yieldStack">
              <view
                class="yieldItem"
                style="border-right: 1rpx solid #8E8C8C; border-bottom: 1rpx solid #8E8C8C;"
              >
                <text class="cellContent2" style="text-align: center;"
                  >近一个月</text
                >
                <text class="cellContent3" style="text-align: center;">{{
                  model.oneMonthRate
                }}</text>
              </view>
              <view
                class="yieldItem"
                style="border-bottom: 1rpx solid #8E8C8C;"
              >
                <text class="cellContent2" style="text-align: center;"
                  >近三个月</text
                >
                <text class="cellContent3" style="text-align: center;">{{
                  model.threeMonthRate
                }}</text>
              </view>
              <view class="yieldItem" style="border-right: 1rpx solid #8E8C8C;">
                <text class="cellContent2" style="text-align: center;"
                  >近六个月</text
                >
                <text class="cellContent3" style="text-align: center;">{{
                  model.sixMonthRate
                }}</text>
              </view>
              <view class="yieldItem">
                <text class="cellContent2" style="text-align: center;"
                  >适合资金</text
                >
                <text class="cellContent2" style="text-align: center;"
                  >10～30万</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </div>
</template>
<script>
import {
  getListDataDecode,
  getMatrixDataDecode,
  get399300LineData
} from '../assets/js/DataAnalyst.js'
import UCharts from '../assets/js/u-charts/u-charts.js'
import defaultKey from '../assets/js/defaults.js'
var _self
var canvaLineA = null
export default {
  data() {
    return {
      img: require('../assets/img/' + this.$store.state.Num + '.png'),
      listTypeButtonArray: [],
      listArrangementTypeButtonArray: [],
      data: '',
      listDataSource: [],
      cWidth: '',
      cHeight: '',
      pixelRatio: 1,
      phoneNumber: '',
      selectedAlgoList: true,
      selectedMyAlgo: false,
      selectedMyAccount: false,
      selectedIndividualStocks: false,
      searchString: '',
      lineData399300: [],
      page: 1,
      size: 20,
      subscribeText: '我要订阅+',
      canvaLineA: null
    }
  },
  methods: {
    // 获取排行榜收益率
    getSortedList: function(e) {
      let search = ''
      if (this.searchString.length > 0) {
        search = this.searchString
      }
      this.showLoading({
        title: '加载数据...'
      })
      this.request({
        url: e,
        data: {
          name: search,
          page: this.page,
          size: this.size
        },
        complete: () => {
          // 停止下拉刷新
          this.stopPullDownRefresh()
          this.hideLoading()
        },
        success: res => {
          const dataArray = res.data.result.rows
          for (const model of dataArray) {
            // model.charData
            model.oneMonthRate = '0.00%'
            model.threeMonthRate = '0.00%'
            model.oneMonthRate = '0.00%'
            model.endTime = model.endTime.slice(0, 10)
            this.listDataSource.push(model)
            const urlString =
              defaultKey.REQUEST_URL_MATRIX_PREFIX +
              defaultKey.REQUEST_URL_ALGO_LIST_NAME +
              defaultKey.REQUEST_URL_MATRIX_SUFFIX +
              model.cnName +
              '.dat'
            this.getMatrixData(urlString, model)
          }
        },
        fail: () => {}
      })
    },

    // 加载我的策略列表
    getMineListData: function(e, mainListRequest) {
      this.showLoading({
        title: '加载数据...'
      })
      this.request({
        url: e,
        responseType: 'arraybuffer',
        complete: () => {
          // 停止下拉刷新
          this.stopPullDownRefresh()
          this.hideLoading()
        },
        success: res => {
          if (res.statusCode !== 200) {
            // 失败处理
            this.listDataSource = []
            this.showErrorMessage('请求失败')
          } else {
            // 成功处理
            var dataBuffer = Buffer.from(res.data)
            this.listDataSource = getListDataDecode(dataBuffer)
            for (const model of this.listDataSource) {
              let urlString = ''
              if (mainListRequest) {
                urlString =
                  defaultKey.REQUEST_URL_MATRIX_PREFIX +
                  defaultKey.REQUEST_URL_ALGO_LIST_NAME +
                  defaultKey.REQUEST_URL_MATRIX_SUFFIX +
                  model.cnName +
                  '.dat'
              } else {
                urlString =
                  defaultKey.REQUEST_URL_MATRIX_PREFIX +
                  this.phoneNumber +
                  defaultKey.REQUEST_URL_MATRIX_SUFFIX +
                  model.cnName +
                  '.dat'
              }
              this.getMatrixData(urlString, model)
            }
          }
        },
        fail: () => {
          // 失败处理
          this.listDataSource = []
          this.showErrorMessage('请求失败')
        }
      })
    },

    // 加载策略模板
    getTemplateList: function() {
      this.showLoading({
        title: '加载数据...'
      })
      this.request({
        url: defaultKey.REQUEST_URL_TEMPLATE_LIST,
        responseType: 'arraybuffer',
        complete: () => {
          // 停止下拉刷新
          this.stopPullDownRefresh()
          this.hideLoading()
        },
        success: res => {
          // 加载模板策略数据成功
          var dataBuffer = Buffer.from(res.data)
          this.listDataSource = getListDataDecode(dataBuffer)
          for (const model of this.listDataSource) {
            const urlString =
              defaultKey.REQUEST_URL_MATRIX_PREFIX +
              defaultKey.REQUEST_URL_ALGO_TEMPLATE_NAME +
              defaultKey.REQUEST_URL_MATRIX_SUFFIX +
              model.cnName +
              '.dat'
            this.getMatrixData(urlString, model)
          }
        },
        fail: () => {
          this.showToast({
            title: '加载策略模板失败！'
          })
        }
      })
    },

    // 加载图表数据
    getMatrixData: function(url, model) {
      this.request({
        url: url,
        data: {},
        header: {},
        responseType: 'arraybuffer',
        success: res => {
          const dataBuffer = Buffer.from(res.data)
          const data = getMatrixDataDecode(dataBuffer, model.cnName)
          model.oneMonthRate =
            (data.oneMonthValue.rate * 100).toString().slice(0, 5) + '%'
          if (
            model.oneMonthRate === 'NaN%' ||
            model.oneMonthRate === '-Infi%'
          ) {
            model.oneMonthRate = '0.00%'
          }
          model.threeMonthRate =
            (data.threeMonthValue.rate * 100).toString().slice(0, 5) + '%'
          if (
            model.threeMonthRate === 'NaN%' ||
            model.threeMonthRate === '-Infi%'
          ) {
            model.threeMonthRate = model.oneMonthRate
          }
          model.sixMonthRate =
            (data.sixMonthValue.rate * 100).toString().slice(0, 5) + '%'
          if (
            model.sixMonthRate === 'NaN%' ||
            model.sixMonthRate === '-Infi%'
          ) {
            model.sixMonthRate = model.threeMonthRate
            const rate = data.rate[data.rate.length - 1].rate
            model.sixMonthRate = (rate * 100).toString().slice(0, 5) + '%'
          }
          const categories = []
          const seriesData = []
          // const lastRate = data.rate[data.rate.length - 1]
          // 组装图表数据
          for (let i = 0; i < data.rate.length; i++) {
            categories.push(data.rate[i].time)
            seriesData.push(data.rate[i].rate)
          }
          const charData = {
            categories: categories,
            series: [{ name: '收益率', data: seriesData }]
          }
          model.charData = charData
          this.request399300LineData(model.cnName, charData)
        },
        fail: res => {
          // 失败处理
          debugger
        }
      })
    },

    // 获取沪深300线图数据
    request399300LineData: function(charName, charData) {
      if (this.lineData399300.length > 0) {
        // 已经获取到沪深300数据则直接显示
        this.show399300Line(charName, charData)
      } else {
        // 未获取到沪深300数据则先获取再显示
        this.request({
          url: 'https://fix.lanmuda.com.cn/algo/day_data_by_symbol0399300.dat',
          responseType: 'arraybuffer',
          success: res => {
            var dataBuffer = Buffer.from(res.data)
            var data = get399300LineData(dataBuffer)
            this.lineData399300 = data
            this.show399300Line(charName, charData)
          },
          fail: res => {
            // 失败处理
            debugger
          }
        })
      }
    },

    // 显示沪深300线到指定图
    show399300Line: function(charName, charData) {
      // 查找该策略对应的沪深300时间段
      // const count = charData.categories.length
      const beginDate = charData.categories[0]
      const firstPrice = this.lineData399300[beginDate]
      const rateArray = []
      for (var i = 0; i < charData.categories.length; i++) {
        const date = charData.categories[i]
        const price = this.lineData399300[date]
        if (typeof price !== 'undefined') {
          const rate = (price - firstPrice) / firstPrice
          rateArray.push(rate)
        }
      }
      const series = { name: '沪深300', data: rateArray }
      charData.series.push(series)
      this.showLineA(charName, charData)
    },

    showLineA: function(canvasId, chartData) {
      canvaLineA = new UCharts({
        $this: _self,
        canvasId: canvasId,
        colors: ['#53A6DB', '#EF853D'],
        type: 'line',
        fontSize: 11,
        legend: { show: false },
        dataLabel: false,
        dataPointShape: false,
        background: '#052341',
        pixelRatio: _self.pixelRatio,
        categories: chartData.categories,
        series: chartData.series,
        animation: true,
        padding: [15, 15, 4, 19],
        xAxis: {
          fontSize: 10,
          fontColor: '#FFFFFF',
          gridColor: '#8E8C8C',
          gridType: 'dash',
          dashLength: 1.5,
          axisLine: false,
          disableGrid: true,
          labelCount: 4,
          rotateLabel: true
        },
        yAxis: {
          disabled: true,
          gridType: 'dash',
          dashLength: 1.5,
          gridColor: '#8E8C8C',
          axisLine: false,
          splitNumber: 5,
          format: val => {
            return val.toFixed(0) + '%'
          }
        },
        width: _self.cWidth * _self.pixelRatio,
        height: _self.cHeight * _self.pixelRatio,
        extra: {
          line: {
            type: 'curve',
            width: 1
          }
        }
      })
    }
  }
}
</script>
